package com.ficv.tucanalmovil;

import android.content.Context;
import android.content.res.AssetManager;
import android.net.Uri;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.IOException;
import java.io.InputStream;

public class WorkaroundWebClient extends WebViewClient {
    private Context mContext;

    public WorkaroundWebClient(Context context) {
        mContext = context;
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view,
            String url) {
        InputStream stream = inputStreamForAndroidResource(url);
        if (stream != null) {
            return new WebResourceResponse(null, null, stream);
        }
        return super.shouldInterceptRequest(view, url);
    }

    private InputStream inputStreamForAndroidResource(String url) {
        final String ANDROID_ASSET = "file:///android_asset/";

        if (url.startsWith(ANDROID_ASSET)) {
            url = url.replaceFirst(ANDROID_ASSET, "");
            try {
                AssetManager assets = mContext.getAssets();
                Uri uri = Uri.parse(url);
                return assets.open(uri.getPath(), AssetManager.ACCESS_STREAMING);
            } catch (IOException e) {}
        }
        return null;
    }
}

